//  新建资源资源的注释
<template>
  <a-card :bordered="false">
    <div class="table-page-search-wrapper">
      <a-form layout="inline">
        <a-form layout="inline">
          <a-row :gutter="48">

            <a-col :md="6" :sm="10">
              <a-form-item label="关键字">
                <a-input v-model="queryParam.keywords" placeholder="名称/年级"/>
              </a-form-item>
            </a-col>

            <a-col :md="5" :sm="24">
              <a-form-item
                  label="学段"
                  :labelCol="labelCol"
                  :wrapperCol="wrapperCol"
              >
                <a-select
                    optionFilterProp="title"
                    mode="default"
                    v-model="queryParam.learning_section_id"
                    placeholder="选择学段"
                >
                  <a-select-option :key="option.id" v-for="option in learningSection" :title="option.name" :disabled="option.disabled" :value="option.id">{{option.name}}</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>

            <a-col :md="5" :sm="24">
              <a-form-item
                  label="年级"
                  :labelCol="labelCol"
                  :wrapperCol="wrapperCol"
              >
                <a-select
                    optionFilterProp="title"
                    v-model="queryParam.grade_id"
                    placeholder="选择年级"
                >

<!--                  <a-select-option :key="option.id" v-for="option in gradeOptions"   :title="option.name" :disabled="option.disabled" :value="option.id">{{option.name}}</a-select-option>-->
                  <a-select-option :key="option.id" v-for="option in gradeTreeOptions"   :title="option.name" :disabled="option.disabled" :value="option.id">{{option.name}}</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>

            <a-col :md="5" :sm="24">
              <a-form-item
                  label="学科"
                  :labelCol="labelCol"
                  :wrapperCol="wrapperCol"
              >
                <a-select
                    optionFilterProp="title"
                    mode="default"
                    v-model="queryParam.subject_id"
                    placeholder="选择学科"
                >
                  <a-select-option :key="option.id" v-for="option in subjectOptions" :title="option.name" :disabled="option.disabled" :value="option.id">{{option.name}}</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>

            <a-col :md="!advanced && 6 || 24" :sm="24">
            <span class="table-page-search-submitButtons" :style="advanced && { float: 'right', overflow: 'hidden' } || {} ">
              <a-button type="primary" @click="onSearch">查询</a-button>
              <a-button style="margin-left: 8px" @click="() => queryParam = {}">重置</a-button>
            </span>
            </a-col>

          </a-row>
        </a-form>
      </a-form>

    </div>

    <div class="table-operator">
      <a-button type="primary" icon="plus" @click="handleAdd" >新建</a-button>
    </div>
    </div>



    <template>
      <s-table
          ref="table"
          size="default"
          :columns="columns"
          :data="loadData"
          :alert="{ show: true, clear: () => { this.selectedRowKeys = [] } }"
          :rowSelection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
      >

        <span slot="status" slot-scope="status,record">
        <a-badge status="success" v-if="status==1" text="显示" />
        <a-badge status="default" v-else text="隐藏" />
      </span>
        <span slot="action" slot-scope="text, record">
        <template >
          <a @click="handleEdit(record)" v-if="$auth('user.edit')">编辑</a>
          <a-divider type="vertical" />
            <a-popconfirm title="确定删除吗" @confirm="onDelete(record)"  okText="确定" cancelText="取消">
    <a href="javascript:;">删除</a>
            </a-popconfirm>
        </template>

      </span>
      </s-table>
    </template>

    <a-modal
        title="操作"
        :width="800"
        v-model="visible"
        @ok="handleOk"
    >
      <a-spin :spinning="saveLoading">
        <a-form :form="form">
          <a-form-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              label="资源名称"
              hasFeedback
          >
            <a-input v-decorator="[
          'name',
          {rules: [{ required: false, message: '请输入班级名称' }]}
        ]"
                     placeholder="请输入资源名称"/>
          </a-form-item>

          <a-form-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              label="资源简介"
              hasFeedback
          >
            <a-input v-decorator="[
          'desc',
          {rules: [{ required: true, message: '请输入资源简介' }]}
        ]"
                     placeholder="请输入资源简介"/>
          </a-form-item>

          <a-form-item
              label="学段"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
          >
            <a-select
                @change="learningSectionChange"
                optionFilterProp="title"
                mode="default"
                v-model="formData.learning_section_id"
                placeholder="选择学段"
            >
              <a-select-option :key="option.id" v-for="option in learningSection" :title="option.name" :disabled="option.disabled" :value="option.id">{{option.name}}</a-select-option>
            </a-select>
          </a-form-item>

          <a-form-item
              label="年级"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
          >
            <a-select
                optionFilterProp="title"
                v-model="formData.grade_id"
                placeholder="选择年级"
            >

              <a-select-option :key="option.id" v-for="option in gradeTreeOptions"   :title="option.name" :disabled="option.disabled" :value="option.id">{{option.name}}</a-select-option>
            </a-select>
          </a-form-item>

          <a-form-item
              label="学科"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
          >
            <a-select
                optionFilterProp="title"
                mode="default"
                v-model="formData.subject_id"
                placeholder="选择学科"
            >
              <a-select-option :key="option.id" v-for="option in subjectOptions" :title="option.name" :disabled="option.disabled" :value="option.id">{{option.name}}</a-select-option>
            </a-select>
          </a-form-item>
          <a-form-item
              label="文件"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              extra="请上传相关文件"
          >
            <file-uploader
                :file-list="formData.file"
            />
          </a-form-item>

<!--          <a-form-item-->
<!--              label="内容详情"-->
<!--              :labelCol="labelCol"-->
<!--              :wrapperCol="wrapperCol"-->
<!--          >-->

<!--            <UEditor  style="width: 400px; height:520px;" :ueditorcontent.sync="formData.content" ></UEditor>-->
<!--          </a-form-item>-->

<!--          <a-form-item-->
<!--              :labelCol="labelCol"-->
<!--              :wrapperCol="wrapperCol"-->
<!--              label="状态"-->
<!--              hasFeedback-->
<!--          >-->
<!--            <r-switch  :formData="formData" field="status" :checkedValue="1" :unCheckedValue="2"  checkedChildren="显示" unCheckedChildren="隐藏" />-->
<!--          </a-form-item>-->
        </a-form>
      </a-spin>
      <template slot="footer">
        <a-button key="cancel" @click="handleCancel">取消</a-button>
        <a-button key="forward" :loading="saveLoading" type="primary" @click="handleOk">保存</a-button>
      </template>
    </a-modal>

  </a-card>
</template>

<script>
import moment from 'moment'
import EditableCell from '@/components/EditableCell/'
import STable from '@/components/table/'
import {resourceAdd,resourceDetail, resourceEdit, resourceDelete, getResourceList, gradeOptions,
  learningSection, subjectOptions, gradeTreeOptions} from '@/api/resource'
import PicUploader from '@/components/PicUploader/'
import RSwitch from '@/components/RSwitch/'
import FileUploader from "@/components/FileUploader/FileUploader/FileUploader"
import {getUserList} from "@/api/user";
import UEditor from '@/components/UEditor/'
import {cateTreeList} from "@/api/exame";


export default {
  name: 'ResourceList',
  components: {
    PicUploader,EditableCell,RSwitch,STable, FileUploader,UEditor
  },
  data () {
    return {
      saveLoading:false,
      visible: false,
//        contentription: '全校班级管理。',
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 12 },
      },
      form: this.$form.createForm(this),
      mdl: {},

      // 高级搜索 展开/关闭
      advanced: false,
      // 查询参数
      queryParam: {
        pageNo:1,
      },
      // 表头
      columns: [
        {
          title: '名称',
          dataIndex: 'name',
          scopedSlots: { customRender: 'name' },
        },
        {
          title: '年级',
          dataIndex: 'grade_name',
        },
        {
          title: '简介',
          dataIndex: 'desc',
          scopedSlots: { customRender: 'desc' },
        },
        {
          table: '操作',
          dataIndex: 'action',
          width: '250px',
          scopedSlots: { customRender: 'action' },
        }
      ],

      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        console.log('loadData');
        console.log(this.queryParam);
        this.queryParam = Object.assign(this.queryParam,parameter);
        return getResourceList(this.queryParam)
            .then(res => {
              console.log('res');
              return res.data
            })
      },
      list:[
      ],
      subjectOptions:[
      ],
      yearOptions:[
      ],
      gradeOptions:[
      ],
      gradeTreeOptions:[
      ],
      learningSection:[
      ],
      formData:{
        name:'',
        pic:[],
        file:[],
        id:0,
        rank:0,
        status:1,
        content:'',
      },
      selectedRowKeys: [],
      selectedRows: [],
    }
  },
  created () {
  },
  computed:{
  },


  mounted(){
    let that = this;
    // that.getGradeOptions();
    // that.getGradeTreeOptions();
    that.getLearningSection();
    that.getSubjectOptions();

  },

  methods: {
    learningSectionChange(){
      // this.formData.learning_section_id = 0;
      this.getGradeTreeOptions();
    },
    getSubjectOptions(){
      let that = this;
      subjectOptions()
          .then(res => {
            console.log(res)
            that.subjectOptions =  res.data
          })
    },
    getGradeOptions(){
      let that = this;
      gradeOptions()
          .then(res => {
            console.log(res)
            that.gradeOptions =  res.data
          })
    },

    getGradeTreeOptions(){
      let that = this;
      gradeTreeOptions({
        learning_section_id: that.formData.learning_section_id
      })
          .then(res => {
            console.log(11111)
            console.log(res.data);
            that.gradeTreeOptions =  res.data;
          })
    },

    getCateOptions(){
      let that = this;
      gradeTreeOptions({
        learning_section_id: that.formData.learning_section_id
      })
          .then(res => {
            that.cateOptions =  res.data;
            that.gradeTreeOptions =  res.data
          })
    },
    getLearningSection(){
      let that = this;
      learningSection()
          .then(res => {
            console.log(res)
            that.learningSection =  res.data
          })
    },
    onSelectChange (selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectedRows = selectedRows
    },
    handleCancel(){
      this.visible = false
    },
    // 增
    handleAdd() {
      let that = this;
      that.visible = true;
      that.form.resetFields();
      that.formData = {
        name:'',
        pic:[],
        file:[],
        version_id:undefined,
        id:0,
        rank:0,
        status:1,
        content:'',

      }
      setTimeout( () =>{
        that.form.setFieldsValue({ ...that.formData });
      });
    },
    // 改
    handleEdit(record) {
      let self = this
      this.visible = true
//      this.form.resetFields();
      self.form.setFieldsValue({
        name:'',
      });
      this.formData.id = record.id;
      resourceDetail({ id: record.id }).then(res => {
        setTimeout(()=>{
          self.form.setFieldsValue({...res.data});
        },1)
        self.formData = {...res.data};
        //new
        self.getCateOptions();
      })
      // console.log(this.mdl)
    },
    // 增改 处理
    handleOk(e) {
      let self = this
      e.preventDefault()
      this.form.validateFields((err, values) => {
        console.log('Received values of form: ', err);
        if (!err) {
          console.log('Received values of form: ', values)
          console.log('Received valuess of formData: ', self.formData)
          self.saveLoading = true;
          if(self.formData.id) {
            resourceEdit({
              id:self.formData.id,
              status:self.formData.status,
              grade_id:self.formData.grade_id,
              subject_id:self.formData.subject_id,
              desc:values.desc,
              name:values.name,
              pic:self.formData.pic,
              file:self.formData.file,
              content:self.formData.content,
              learning_section_id:self.formData.learning_section_id,

            }).then(res => {
              self.$message.success('修改成功')
              self.$refs.table.refresh(true)
              self.visible = false;
              self.saveLoading = false;
            }).catch(err =>{
              self.$message.error(err.data.msg);
              self.saveLoading = false;
            })
          }else{

            console.log("111111111111111111")
            console.log(self.formData)
            resourceAdd({
              status:self.formData.status,
              grade_id:self.formData.grade_id,
              subject_id:self.formData.subject_id,
              desc:values.desc,
              name:values.name,
              pic:self.formData.pic,
              file:self.formData.file,
              content:self.formData.content,
              learning_section_id:self.formData.learning_section_id,


            }).then(res => {
              self.$message.success('新增成功')
              self.$refs.table.refresh(true)
              self.visible = false
              self.saveLoading = false;
            }).catch(err =>{
              self.$message.error(err.data.msg);
              self.saveLoading = false;
            })
          }
        }
      })
    },

    // 查
    onSearch() {
      let self = this;
      self.$refs.table.refresh(true)
    },

    // 删
    onDelete(record) {
      let self = this
      resourceDelete({ id: record.id  }).then(res => {
        self.$message.success('删除成功')
        self.$refs.table.refresh(true)
      }).catch(err =>{
        self.$message.error(err.data.msg)
      })
    },
  },
  watch: {
    /*
     'selectedRows': function (selectedRows) {
     this.needTotalList = this.needTotalList.map(item => {
     return {
     ...item,
     total: selectedRows.reduce( (sum, val) => {
     return sum + val[item.dataIndex]
     }, 0)
     }
     })
     }
     */
  }
}
</script>